package com.yanhao.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.yanhao.R
import com.yanhao.bean.Article
import com.yanhao.databinding.ItemArticleAdapterBinding

class ArticleAdapter(val mDatas: MutableList<Article>) :
    RecyclerView.Adapter<ArticleAdapter.MyViewHolder>() {


    /**
     * item点击事件
     * @param Int 角标
     * @param View 点击的View
     */
    private var mOnItemClickListener: ((Int, View) -> Unit)? = null


    /**
     * item中字view的点击事件，需要子类做具体触发
     * @param Int 角标
     * @param View 点击的View
     */
    private var mOnItemChildClickListener: ((Int, View) -> Unit)? = null


    /**
     * 注册item点击事件
     */
    fun setOnItemClickListener(onItemClickListener: ((Int, View) -> Unit)? = null) {
        this.mOnItemClickListener = onItemClickListener
    }

    fun setonItemChildClickListener(onItemChildClickListener: ((Int, View) -> Unit)? = null) {
        this.mOnItemChildClickListener = onItemChildClickListener
    }


    class MyViewHolder(private val binding: ItemArticleAdapterBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun getBinding(): ItemArticleAdapterBinding {
            return binding
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val view =
            ItemArticleAdapterBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return MyViewHolder(view)
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        var article = mDatas[position]
        var collect = article.collect
        holder.getBinding().apply {
            tvTime.text = article.niceDate
            tvTitle.text = article.title
            tvSuperChapterName.text = article.superChapterName
        }
        if (collect) {
            holder.getBinding().ivCollect.setBackgroundResource(R.drawable.ic_collect_checked)
        } else {
            holder.getBinding().ivCollect.setBackgroundResource(R.drawable.ic_collect_unchecked_stroke)
        }
        holder.itemView.setOnClickListener {
            mOnItemClickListener?.invoke(position, it)
        }

        holder.getBinding().ivCollect.setOnClickListener {
            mOnItemChildClickListener?.invoke(position, it)
        }

    }

    override fun getItemCount(): Int = mDatas.size



}